package com.meilai.project.controller.mini;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.meilai.project.constant.BossUserEnum;
import com.meilai.project.controller.mini.dto.CustomerNextVisitDTO;
import com.meilai.project.controller.mini.dto.MiniCustomerInfoDTO;
import com.meilai.project.controller.mini.dto.customer.CustomerDto;
import com.meilai.project.controller.mini.dto.customer.CustomerFlowRemoveDTO;
import com.meilai.project.dto.CommonResult;
import com.meilai.project.dto.base.ApiResult;
import com.meilai.project.dto.business.customer.CustomerInfoFlowDTO;
import com.meilai.project.dto.workflow.WorkFlowExtraCheckDTO;
import com.meilai.project.dto.workflow.WorkFlowRomoveDTO;
import com.meilai.project.entity.business.customer.CustomerContact;
import com.meilai.project.entity.business.customer.CustomerInfo;
import com.meilai.project.entity.business.customer.CustomerPutStorage;
import com.meilai.project.entity.business.customer.CustomerVisitComments;
import com.meilai.project.exception.CommonException;
import com.meilai.project.service.business.customer.*;
import com.meilai.project.service.business.dataLevel.DataQueryBusinessLevelService;
import com.meilai.project.util.ThreadLocalUserUtil;
import com.meilai.project.vo.business.customer.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户信息表 前端控制器
 * </p>
 *
 * @author xhy
 * @since 2022-01-06
 */

@RestController
@RequestMapping("api/mini/customerInfo")
@Api(tags = "小程序-客户")
public class MiniCustomerInfoController {

    @Autowired
    private CustomerInfoService service;

    @Autowired
    private CustomerInfoFlowService customerInfoFlowService;

    @Autowired
    private CustomerContactService customerContactService;

    @Autowired
    private CustomerPutStorageService customerPutStorageService;

    @Autowired
    private DataQueryBusinessLevelService dataQueryBusinessLevelService;

    @Autowired
    private MiniCustomerEditFlowService miniCustomerEditFlowService;

    @GetMapping("/page")
    @ApiOperation("分页查询")
    public CommonResult page(@RequestParam(name = "page", defaultValue = "1") Integer page,
                             @RequestParam(name = "page_size", defaultValue = "10") Integer page_size,
                             @RequestParam(name = "is_my_customer_page") Boolean is_my_customer_page,
                             @RequestParam(name = "name", required = false) String name,
                             @RequestParam(name = "industry_id", required = false) Long industry_id,
                             @RequestParam(name = "type") Integer type,
                             @RequestParam(name = "maintenance_staff_id", required = false) Long maintenance_staff_id) {
        return new CommonResult().success(service.page(page, page_size, name, industry_id, is_my_customer_page, type, maintenance_staff_id));
    }

    @GetMapping("/allPage")
    @ApiOperation("分页查询，显示所有客户")
    public CommonResult allPage(@RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "page_size", defaultValue = "10") Integer page_size, @RequestParam(name = "name", required = false) String name, @RequestParam(name = "industry_id", required = false) Long industry_id, @RequestParam(name = "follow_up") Boolean follow_up, @RequestParam(name = "deptId", required = false) Long deptId) {
        return new CommonResult().success(service.allPage(page, page_size, name, industry_id, follow_up, deptId));
    }

    @GetMapping("list-all")
    @ApiOperation("查询当前人跟进的所有客户")
    public ApiResult<CustomerInfo> listAll() {
        return ApiResult.ok(service.listAll());
    }

    @GetMapping("company-list-all")
    @ApiOperation("查询公司的所有客户")
    public ApiResult<CustomerInfo> companyListAll() {
        return ApiResult.ok(service.companyListAll());
    }

    @GetMapping("/one")
    @ApiOperation("根据ID获取客户信息")
    public CommonResult one(@RequestParam(name = "id") Long id) {
        return new CommonResult().success(service.getDeteil(id));
    }

    @GetMapping("/getContactInfoById")
    @ApiOperation("根据ID获取客户联系人")
    public ApiResult<List<CustomerContact>> getContactInfoById(@RequestParam(name = "id") Long id) {
        return ApiResult.ok(customerContactService.queryList(id));
    }

    @GetMapping("/getPutStorageById")
    @ApiOperation("根据ID获取入库信息")
    public ApiResult<List<CustomerPutStorage>> getPutStorageById(@RequestParam(name = "id") Long id) {
        return ApiResult.ok(customerPutStorageService.list(Wrappers.<CustomerPutStorage>lambdaQuery().eq(CustomerPutStorage::getCustomer_id, id)));
    }


    @PostMapping("/edit")
    @ApiOperation("指派销售")
    public CommonResult edit(@RequestParam(name = "id") Long id, @RequestParam(name = "maintenance_staff_id") Long maintenance_staff_id) {
        return new CommonResult().success(service.edit(id, maintenance_staff_id));
    }


    @GetMapping("/advanceList")
    @ApiOperation("推送动作集合")
    public ApiResult<List<CustomerAdvanceVO>> advanceList() {
        return ApiResult.ok(service.advanceList());
    }

    @PostMapping("/addNextVisitDate")
    @ApiOperation("添加下次跟进时间")
    public CommonResult addNextVisitDate(@RequestBody CustomerNextVisitDTO dto) {
        if (dto.getId() == null) {
            throw new CommonException("客户id不能为空");
        }
        return new CommonResult().success(service.update(Wrappers.<CustomerInfo>lambdaUpdate().set(CustomerInfo::getNext_visit_time, dto.getDate()).set(CustomerInfo::getPurpose, dto.getPurpose()).eq(CustomerInfo::getId, dto.getId())));
    }

    @GetMapping("/visitRecordList")
    @ApiOperation("根据客户ID获取拜访记录")
    public ApiResult<Page<CustomerFollowVO>> visitRecordList(@RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "page_size", defaultValue = "10") Integer page_size, @RequestParam("customer_id") Long customer_id, @RequestParam(value = "contact_name", required = false) String contact_name, @RequestParam(value = "begin_date", required = false) @JsonFormat(pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin_date, @RequestParam(value = "end_date", required = false) @JsonFormat(pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end_date) {
        return ApiResult.ok(service.visitRecordList(page, page_size, customer_id, contact_name, begin_date, end_date));
    }


    @GetMapping("/companyAdvanceList")
    @ApiOperation("推送动作集合")
    public CommonResult companyAdvanceList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                           @RequestParam(value = "page_size", defaultValue = "10") Integer page_size,
                                           @RequestParam(value = "user_id", required = false) Long user_id,
                                           @RequestParam(value = "type", required = false) Integer type,
                                           @RequestParam(value = "name", required = false) String name,
                                           @RequestParam(value = "year") Integer year,
                                           @RequestParam(value = "month") Integer month) {
        // todo 解决小程序卡顿问题 修改为分页
        Page<CompanyCustomerAdvanceVO> result = new Page(page, page_size);
        List<Long> boss_ids = null;
        // 检查type
        if (type != null) {
            // 获取boss_ids
            boss_ids = new ArrayList<>(Arrays.asList(BossUserEnum.values())).stream().map(BossUserEnum::getId).collect(Collectors.toList());
        }
        List<CompanyCustomerAdvanceVO> companyCustomerAdvanceVOS = service.queryCustomerInfoPageOrderByFollowDesc(result, type, boss_ids, name, user_id);
        List<Long> ids = companyCustomerAdvanceVOS.stream().map(CompanyCustomerAdvanceVO::getId).collect(Collectors.toList());
        List<CompanyCustomerAdvanceVO> data = service.companyAdvanceList(year, month, ids);
        result.setRecords(data);
        return new CommonResult().success(result);
    }

    @GetMapping("/getContactById")
    @ApiOperation("获取联系人")
    public CommonResult getContactById(@RequestParam("id") Long id) {
        return new CommonResult().success(service.getContactById(id));
    }

    @GetMapping("/visitCommentsPage")
    @ApiOperation("历史批注信息")
    public ApiResult<Page<CustomerVisitComments>> visitCommentsPage(@RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "page_size", defaultValue = "10") Integer page_size, @RequestParam("customer_id") Long customer_id, @RequestParam(value = "comments", required = false) String comments) {
        return ApiResult.ok(service.visitCommentsPage(page, page_size, customer_id, comments));
    }

    @PostMapping("/save")
    @ApiOperation("临时保存")
    public ApiResult<Boolean> save(@RequestBody CustomerDto dto) {
        Long id = ThreadLocalUserUtil.get().getId();
        dto.getData().setMaintenance_staff_id(id);
        return ApiResult.ok(customerInfoFlowService.save(dto.getData(), true, dto.getWfData_id()));
    }

    @PostMapping("/saveAndStartFlow")
    @ApiOperation("保存并开启流程")
    public ApiResult<Boolean> saveAndStartFlow(@RequestBody CustomerDto dto) {
        Long id = ThreadLocalUserUtil.get().getId();
        dto.getData().setMaintenance_staff_id(id);
        return ApiResult.ok(customerInfoFlowService.saveAndStartFlow(dto.getData(), dto.getWfData_id()));
    }

    @PostMapping("/check")
    @ApiOperation("审批")
    public CommonResult check(@RequestBody CustomerDto dto) {
        return new CommonResult().success(customerInfoFlowService.check(dto.getData(), dto.getIsCover(), dto.getIsReturn(), dto.getOpinion()));
    }

    @PostMapping("/remove")
    @ApiOperation("删除记录")
    public ApiResult<Boolean> remove(@RequestBody CustomerFlowRemoveDTO dto) {
        return ApiResult.ok(customerInfoFlowService.remove(dto.getFlow_id(), dto.getWfData_id()));
    }

    @GetMapping("/flow/one")
    @ApiOperation("根据审批ID获取客户信息")
    public ApiResult<CustomerInfoFlowDTO> flowDetail(@RequestParam(name = "id") Long id) {
        return ApiResult.ok(customerInfoFlowService.getFlowDtoById(id));
    }

    @PostMapping("/equalsData")
    @ApiOperation("判断用户基本数据信息是否有修改")
    public ApiResult<List<CustomerChangeVO>> equalsData(@RequestBody CustomerInfoFlowDTO dto) {
        return ApiResult.ok(customerInfoFlowService.equalsData(dto));
    }

    @PostMapping("/actualDelete")
    @ApiOperation("彻底删除记录")
    public ApiResult<Boolean> actualDelete(@RequestBody CustomerFlowRemoveDTO dto) {
        return ApiResult.ok(customerInfoFlowService.actualDelete(dto.getFlow_id(), dto.getWfData_id()));
    }

    @PostMapping("/add/linkUser")
    @ApiOperation("添加联系人")
    public ApiResult<Boolean> addLinkUser(@RequestBody CustomerContact dto) {
        Long user_id = ThreadLocalUserUtil.get().getId();
        int level = dataQueryBusinessLevelService.getUserMaxLevel("customer_contact", user_id);
        dto.setLevel_num(level);
        return ApiResult.ok(customerContactService.save(dto));
    }

    @PostMapping("/add/putStorage")
    @ApiOperation("添加入库信息")
    public ApiResult<Boolean> addPutStorage(@RequestBody CustomerPutStorage dto) {
        return ApiResult.ok(customerPutStorageService.save(dto));
    }

    @PostMapping("/edit/save")
    @ApiOperation("修改客户信息临时保存")
    public ApiResult<Boolean> editSave(@RequestBody MiniCustomerInfoDTO dto) {
        return ApiResult.ok(miniCustomerEditFlowService.save(dto));
    }

    @PostMapping("/edit/submit")
    @ApiOperation("修改客户信息提交")
    public ApiResult<Boolean> editSubmit(@RequestBody MiniCustomerInfoDTO dto) {
        return ApiResult.ok(miniCustomerEditFlowService.begin(dto));
    }

    @PostMapping("/edit/pass")
    @ApiOperation("审批")
    public CommonResult pass(@RequestBody WorkFlowExtraCheckDTO dto) {
        return new CommonResult().success(miniCustomerEditFlowService.pass(dto));
    }

    @PostMapping("/edit/returnBack")
    @ApiOperation("审批")
    public CommonResult editReturnBack(@RequestBody WorkFlowExtraCheckDTO dto) {
        return new CommonResult().success(miniCustomerEditFlowService.returnBack(dto));
    }

    @PostMapping("/edit/remove")
    @ApiOperation("删除记录")
    public ApiResult<Boolean> editRemove(@RequestBody WorkFlowRomoveDTO dto) {
        return ApiResult.ok(miniCustomerEditFlowService.delete(dto.getId()));
    }

    @PostMapping("/edit/actualDelete")
    @ApiOperation("彻底删除记录")
    public ApiResult<Boolean> editActualDelete(@RequestBody WorkFlowRomoveDTO dto) {
        return ApiResult.ok(miniCustomerEditFlowService.actualDelete(dto.getId()));
    }

    @GetMapping("/edit/detail")
    @ApiOperation("详情")
    public ApiResult<MiniCustomerEditFlowVO> editDetail(@RequestParam(value = "id") Long id) {
        return ApiResult.ok(miniCustomerEditFlowService.getOneById(id));
    }
}

